<template>
  <div class="app">
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="文档编号" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.docEntry" placeholder="文档编号" />
        </a-form-item>
        <a-form-item label="文档名称" class="smart-query-form-item">
          <a-input style="width: 200px" v-model:value="queryForm.name" placeholder="文档名称" />
        </a-form-item>
        <a-form-item label="文档类型" class="smart-query-form-item">
          <FiletypeTreeSelect style="width: 350px" key="docEntry" v-model:value="queryForm.typeId"></FiletypeTreeSelect>
        </a-form-item>

        <a-form-item class="smart-query-form-item">
          <a-button-group>
            <a-button type="primary" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" class="smart-margin-left10">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card :bordered="false" :hoverable="true">
      <!---------- 表格操作行 begin ----------->
      <a-row class="smart-table-btn-block">
        <a-button-group>
          <a-button v-privilege="'file:docment:add'" @click="add" type="primary">
            <template #icon>
              <PlusOutlined />
            </template>
            新建
          </a-button>
        </a-button-group>
        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
        </div>
      </a-row>
      <!---------- 表格操作行 end ----------->

      <!---------- 表格 begin ----------->
      <a-table
        :scroll="{ x: 600, y: 650 }"
        :dataSource="tableData"
        :columns="columns"
        rowKey="docEntry"
        :loading="tableLoading"
        :pagination="false"
        @resizeColumn="handleResizeColumn"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'name'">
            <a @click="onTo(record.docEntry)">{{ text }} </a>
          </template>
          <template v-if="column.dataIndex === 'docPrivate'">
            <a-tag v-if="text === 'A'" color="#87d068">公开</a-tag>
            <a-tag v-if="text === 'B'" color="#f50">私密</a-tag>
          </template>

          <template v-if="column.dataIndex === 'approved'">
            <a-tag v-if="text" color="#87d068">已审核</a-tag>
            <a-tag v-if="!text" color="#ff5500">未审核</a-tag>
          </template>
        </template>
      </a-table>
      <!---------- 表格 end ----------->

      <div class="smart-query-table-page">
        <!-- 修改分页组件，支持手动输入每页大小 -->
        <div class="pagination-container">
          <a-pagination
            :showSizeChanger="false"
            showQuickJumper
            show-less-items
            v-model:current="queryForm.pageNum"
            :pageSize="queryForm.pageSize"
            :total="total"
            @change="queryData"
            :show-total="(total) => `共${total}条`"
          />

          <!-- 手动输入每页大小的控件 -->
          <div class="page-size-input">
            <span class="page-size-text">每页条数：</span>
            <a-input-number
              v-model:value="customPageSize"
              :min="1"
              :max="100"
              :precision="0"
              style="width: 100px"
              placeholder="输入条数"
              @change="handlePageSizeChange"
            />
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>
<script setup>
  import { reactive, ref, onMounted, watch } from 'vue';
  import { docmentApi } from '/@/api/business/file/docment-api.js';
  import { PAGE_SIZE_OPTIONS } from '/src/constants/common-const';
  import { smartSentry } from '/src/lib/smart-sentry';
  import TableOperator from '/src/components/support/table-operator/index.vue';
  import { useRouter, useRoute } from 'vue-router';
  import { columns } from '/@/views/business/file/docmentData/data.js';
  import FiletypeTreeSelect from '/@/views/business/file/filetypeData/components/filetype-tree-select.vue';
  import { SearchOutlined, ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue';

  // 路由实例
  const router = useRouter();
  const route = useRoute();

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    pageNum: 1,
    pageSize: 20,  // 默认每页20条
    docEntry: null,
    name: null,
    typeId: null,
  };

  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 自定义每页大小（用于输入框双向绑定）
  const customPageSize = ref(queryForm.pageSize);

  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 监听queryForm.pageSize变化，同步到输入框
  watch(
    () => queryForm.pageSize,
    (newVal) => {
      customPageSize.value = newVal;
    }
  );

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 处理每页大小变更
  function handlePageSizeChange(value) {
    if (value && value !== queryForm.pageSize) {
      // 输入有效且与当前值不同时才变更
      queryForm.pageSize = value;
      queryForm.pageNum = 1;  // 变更页大小时重置到第一页
      queryData();
    }
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await docmentApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  function onTo(item) {
    router.push({
      path: 'docmenta',
      query: {
        type: 'info',
        docEntry: item,
        // 携带当前分页状态到详情页
        listPageNum: queryForm.pageNum,
        listPageSize: queryForm.pageSize
      }
    });
  }

  function add() {
    router.push({ path: 'docmenta', query: { type: 'new', docEntry: null } });
  }

  function handleResizeColumn(w, col) {
    col.width = w;
  }

  onMounted(() => {
    // 从路由参数中获取分页信息，如果有的话
    const { pageNum, pageSize } = route.query;
    if (pageNum) {
      queryForm.pageNum = Number(pageNum);
    }
    if (pageSize) {
      queryForm.pageSize = Number(pageSize);
      customPageSize.value = Number(pageSize);
    }
    queryData();
  });
</script>
<style scoped>
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
  }

  .page-size-input {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .page-size-text {
    color: rgba(0, 0, 0, 0.65);
  }
</style>
